package com.y.system.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.y.common.base.BaseController;
import com.y.core.annotation.Before;
import com.y.core.constant.Const;
import com.y.core.constant.PlatForm;
import com.y.core.plugins.dao.Blade;
import com.y.core.shiro.ShiroKit;
import com.y.core.toolbox.Func;
import com.y.core.toolbox.ajax.RestResult;
import com.y.core.toolbox.kit.LogKit;
import com.y.core.toolbox.log.BladeLogManager;
import com.y.system.meta.intercept.LoginValidator;
import com.y.system.model.LoginLog;

@RestController
public class TokenController extends BaseController implements Const {
	@Before(LoginValidator.class)
	@ResponseBody
	@PostMapping("/token")
	public RestResult login(HttpServletRequest request, HttpServletResponse response) {
		String account = getParameter("account");
		String password = getParameter("password");
		Subject currentUser = ShiroKit.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
		token.setRememberMe(true);
		try {
			currentUser.login(token);
		} catch (UnknownAccountException e) {
			LOGGER.error("账号不存在!", e);
			return restError("账号不存在");
		} catch (DisabledAccountException e) {
			LOGGER.error("账号未启用!", e);
			return restError("账号未启用");
		} catch (IncorrectCredentialsException e) {
			LOGGER.error("密码错误!", e);
			return restError("密码错误");
		} catch (RuntimeException e) {
			LOGGER.error("未知错误,请联系管理员!", e);
			return restError("未知错误,请联系管理员");
		}
		doLog(ShiroKit.getSession(), "Token获取成功");
		return restSuccess("get Token success,the token at 90 minute invalid.").success(PlatForm.getToken(token.getUsername()));
	}

	private void doLog(Session session, String type) {
		if (!BladeLogManager.isDoLog()) {
			return;
		}
		try {
			LoginLog log = new LoginLog();
			String msg = Func.format("[sessionID]: {} [sessionHost]: {} [sessionHost]: {}", session.getId(),
					session.getHost(), session.getTimeout());
			log.setLogname(type);
			log.setMethod(msg);
			log.setCreatetime(new Date());
			log.setSucceed("1");
			log.setUserid(Func.toStr(ShiroKit.getUser().getId()));
			Blade.create(LoginLog.class).save(log);
		} catch (Exception ex) {
			LogKit.logNothing(ex);
		}
	}
}
